package cih;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cci.CtrlInterno;
import cci.CtrlPrincipal;
import cdp.Pessoa;
import cdp.Usuario;

@WebServlet(name = "PagCadastro", urlPatterns = {"/PagCadastro"})
public class PagCadastro extends HttpServlet{
	private CtrlInterno ctrl = CtrlInterno.getInstance();
	
	HttpServletRequest request;
	HttpServletResponse response;
	RequestDispatcher dispatcher;
	HttpSession session;

	private String opcao;
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
		
		this.opcao = (String) request.getParameter("opcao");
		
		this.verificaOperacao();
    }
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {   
        processRequest(request, response);
    }
	
	protected void verificaOperacao()
	{
		if (opcao == null)
		{
			//erro
		}
		else
		{			
			System.out.println("Entrou no else");
			switch(opcao)
			{
				case "voltar": this.voltar(); break;
				case "salvar": this.salvarPessoa(); break;
				
				default: break;
			}
		}
	}
	
	private void salvarPessoa()
	{	
		ArrayList<Object> atributos = new ArrayList<Object>();
		
		String senha = (String) request.getParameter("senha");
		String confirmacaoSenha = (String) request.getParameter("confirmacaoSenha");
		
		if (senha.equals(confirmacaoSenha))
		{		
			try {
				atributos.add(request.getParameter("nome"));
				atributos.add(request.getParameter("eMail"));
				atributos.add(request.getParameter("senha"));
				
				ctrl.incluirPessoa(atributos);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			} catch (ServletException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else
		{
			//erro
		}	
	}
	
	private void voltar()
	{
		try {
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
